package com.fingard.dsp.bank.directbank.czb01;

import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.bankInterface.ISubAccount;
import com.fingard.dsp.bank.reqrespobj.subaccount.ReqQrySubAccount;
import com.fingard.dsp.bank.reqrespobj.subaccount.ReqUpdateSubAccount;
import com.fingard.dsp.bank.reqrespobj.subaccount.RetAtsRecUpdate;
import com.fingard.dsp.bank.reqrespobj.subaccount.RetAtsSubAccountInfo;
import com.fingard.dsp.bank.reqrespobj.subaccount.detail.RetAtsSubAccountDetail;
import com.fingard.dsp.bank.reqrespobj.subaccount.detail.RetUpdateSubAccount;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;
import org.apache.commons.net.ftp.FTPClient;

import java.io.File;

/**
 * @Description TODO
 * @Author xtt
 * @Date $ $
 **/
public class CZB01SubAccount extends CZB01Base implements ISubAccount {
    @Override
    public RetAtsSubAccountInfo querySubAccountInfo(ReqQrySubAccount p_subAccount) throws Exception {
        RetAtsSubAccountInfo retAts = new RetAtsSubAccountInfo(p_subAccount.reqHeader);
        retAts.writeStart();
        try {
            int pageno = 1;
            String totalPages = "";
            while (pageno != 0) {
                CZB01Header bankHeader = new CZB01Header();
                bankHeader.transCode = "510008";
                bankHeader.reqSeqNo = p_subAccount.reqHeader.transSeqID;

                XmlTextWriter xmlWriter = new XmlTextWriter();
                writeCommonHeader(xmlWriter, bankHeader);
                xmlWriter.writeStartElement("body");
                xmlWriter.writeElementString("customer_no", p_subAccount.customerNo);
                xmlWriter.writeElementString("sub_account", p_subAccount.subAccount);
                xmlWriter.writeElementString("status", p_subAccount.subAccStatus);
                xmlWriter.writeElementString("pageno", pageno + "");
                xmlWriter.writeEndElement();//body
                xmlWriter.writeEndElement();//ap
                xmlWriter.writeEndDocument();

                String[] retStrArr = sendToBank(xmlWriter.toXmlString());
                if (retStrArr[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);

                    if (tmpBkReader != null) {
                        String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                        String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                        if ("0000".equals(tmpRetCode)) {
                            //交互成功
                            retAts.writeRespCode("0");
                            retAts.writeRespInfo("请求成功");
                            //读取数据
                            while (tmpBkReader.read("/ap/body/record")) {
                                RetAtsSubAccountDetail tmpRetDetail = new RetAtsSubAccountDetail();
                                tmpRetDetail.serialNo = tmpBkReader.readedXElement.getSingleText("id");//序号
                                tmpRetDetail.customerName = tmpBkReader.readedXElement.getSingleText("customer_name");
                                tmpRetDetail.customerNameEn = tmpBkReader.readedXElement.getSingleText("customer_name_en");
                                tmpRetDetail.subAccount = tmpBkReader.readedXElement.getSingleText("sub_account");
                                tmpRetDetail.customerNo = convertCurToATS(tmpBkReader.readedXElement.getSingleText("customer_no"));
                                tmpRetDetail.contactName1 = tmpBkReader.readedXElement.getSingleText("contact_name1");
                                tmpRetDetail.contactTel1 = tmpBkReader.readedXElement.getSingleText("contact_tel1");
                                tmpRetDetail.contactEmail1 = tmpBkReader.readedXElement.getSingleText("contact_email1");
                                tmpRetDetail.contactName2 = tmpBkReader.readedXElement.getSingleText("contact_name2");
                                tmpRetDetail.contactTel2 = tmpBkReader.readedXElement.getSingleText("contact_tel2");
                                tmpRetDetail.contactEmail2 = tmpBkReader.readedXElement.getSingleText("contact_email2");
                                tmpRetDetail.mode = tmpBkReader.readedXElement.getSingleText("mode");
                                tmpRetDetail.status = tmpBkReader.readedXElement.getSingleText("status");
                                tmpRetDetail.respCode = "0";
                                tmpRetDetail.respInfo = tmpRetInfo;
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                            totalPages = tmpBkReader.getFirstText("total_pages");//总页数
                            if (totalPages != null && Integer.valueOf(totalPages) > pageno) {
                                pageno++;
                            } else {
                                pageno = 0;//结束
                            }
                        } else {
                            retAts.writeRespCode("-1");
                            retAts.writeRespInfo(tmpRetInfo);
                            pageno = 0;//结束
                        }
                    } else {
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo(tmpSbMsg.toString());
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(retStrArr[1]);
                    pageno = 0;//结束
                }
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }

    @Override
    public RetAtsRecUpdate maintenanceSubAccountInfo(ReqUpdateSubAccount p_subAccount) throws Exception {
        RetAtsRecUpdate retAts = new RetAtsRecUpdate(p_subAccount.reqHeader);
        retAts.writeStart();
        RetAtsRecUpdate detail = new RetAtsRecUpdate(p_subAccount.reqHeader);
        try {
            //查询序列号
            CZB01Header bankHeader01 = new CZB01Header();
            bankHeader01.transCode = "510008";
            bankHeader01.reqSeqNo = p_subAccount.reqHeader.transSeqID;

            XmlTextWriter xmlWriter01 = new XmlTextWriter();
            writeCommonHeader(xmlWriter01, bankHeader01);
            xmlWriter01.writeStartElement("body");
            xmlWriter01.writeElementString("customer_no", this.getBankConfig().getMapValueByKey("customerNo",p_subAccount.subAccount));
            xmlWriter01.writeElementString("sub_account", p_subAccount.subAccount);
            xmlWriter01.writeElementString("status", "1");
            xmlWriter01.writeElementString("pageno", "0");
            xmlWriter01.writeEndElement();//body
            xmlWriter01.writeEndElement();//ap
            xmlWriter01.writeEndDocument();

            String[] retStrArr01 = sendToBank(xmlWriter01.toXmlString());
            if(retStrArr01[0].length() == 0){
                StringBuilder tmpSbMsg01 = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr01[1], tmpSbMsg01);

                if (tmpBkReader != null) {
                    p_subAccount.serialNo = tmpBkReader.getFirstText("/ap/body/record/id");
                    if(StringHelper.isNullOrEmpty(p_subAccount.serialNo)){
                        retAts.writeRespCode("-1");
                        retAts.writeRespInfo("根据子账户查询序列号失败，请检查子账户是否正确");
                        retAts.writeEnd();
                        return retAts;
                    }
                }
            }
            //修改删除必传序号
            if (p_subAccount.operType != null && !("1").equals(p_subAccount.operType)) {
                if (p_subAccount.serialNo == null) {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo("修改或删除时，序号不能为空");
                    retAts.writeEnd();
                    return retAts;
                }
            }
            CZB01Header bankHeader = new CZB01Header();
            bankHeader.transCode = "510009";
            bankHeader.reqSeqNo = p_subAccount.reqHeader.transSeqID;

            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, bankHeader);
            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("oper_type", p_subAccount.operType);
            xmlWriter.writeElementString("customer_name", p_subAccount.customerName);
            xmlWriter.writeElementString("customer_name_en", p_subAccount.customerNameEn);
            xmlWriter.writeElementString("sub_account", p_subAccount.subAccount);

            xmlWriter.writeElementString("contact_name1", p_subAccount.contactName1);
            xmlWriter.writeElementString("contact_tel1", p_subAccount.contactTel1);
            xmlWriter.writeElementString("contact_email1", p_subAccount.contactEmail1);
            xmlWriter.writeElementString("contact_name2", p_subAccount.contactName2);
            xmlWriter.writeElementString("contact_tel2", p_subAccount.contactTel2);
            xmlWriter.writeElementString("contact_email2", p_subAccount.contactEmail2);
            xmlWriter.writeElementString("mode", "3");
            xmlWriter.writeElementString("id", p_subAccount.serialNo);
            String fileName =  p_subAccount.fileName;
            xmlWriter.writeElementString("file_name", fileName);
            //FTP下载文件，再上传文件到前置机上
            if(StringHelper.hasAnyChar(fileName)){
                //本地临时文件目录
                String uploadFilePath = bankFront.serverUpload;
                FtpSet ftpSet = bankFront.getFtpSet("SubAccountFtp");
                String downFilePath = ftpSet.downDir;
                WriteBankLogLn("FTP下载地址" + ftpSet.serverIP + ":" + ftpSet.port);
                WriteBankLogLn("开始下载服务器文件" + downFilePath + "至" + uploadFilePath);
                FtpPortClient ftpPtClient = new FtpPortClient(ftpSet);
                ftpPtClient.connect();
                FtpReceiver tmpReceiver = ftpPtClient.downloadFile(fileName,uploadFilePath + fileName);
                if (tmpReceiver.connState.length() == 0 && tmpReceiver.isCompleted) {
                    WriteBankLogLn("下载FTP上文件成功，已完成上传前置机，文件名：" + fileName);
                }
                //计算文件MD5
                String fileMD5 = getFileMD5(uploadFilePath + fileName);
                xmlWriter.writeElementString("file_md5",fileMD5);
            }
            xmlWriter.writeEndElement();//body
            xmlWriter.writeEndElement();//ap
            xmlWriter.writeEndDocument();
            //FTP下载文件，再上传文件到前置机上
            String[] retStrArr = sendToBank(xmlWriter.toXmlString(),p_subAccount.reqHeader.transType,p_subAccount.reqHeader.transType);
            if (retStrArr[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(retStrArr[1], tmpSbMsg);

                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/ap/head/ret_code");
                    String tmpRetInfo = tmpBkReader.getFirstText("/ap/head/ret_info");
                    if ("0000".equals(tmpRetCode)) {
                        detail.reqSeqID = p_subAccount.reqHeader.transSeqID;
                        detail.respCode = "0";
                        detail.respInfo = "交易成功";
                        detail.transState = "1";
                        detail.payInfoCode = tmpRetCode;
                        detail.exporterCode = p_subAccount.subAccount;
                        retAts.writeXml(detail);
                    } else {
                        detail.reqSeqID = p_subAccount.reqHeader.transSeqID;
                        detail.respCode = "-1";
                        detail.respInfo = "交易失败";
                        detail.transState = "2";
                        detail.payInfoCode = tmpRetCode;
                        retAts.writeXml(detail);
                    }
                } else {
                    retAts.writeRespCode("-1");
                    retAts.writeRespInfo(tmpSbMsg.toString());
                }
            } else {
                retAts.writeRespCode("-1");
                retAts.writeRespInfo(retStrArr[1]);
            }
        } catch (Exception e) {
            retAts.writeRespCode("-1");
            retAts.writeRespInfo(e.getMessage());
            e.printStackTrace();
        }
        retAts.writeEnd();
        return retAts;
    }
}
